<template>
  <div style="width: 100%">
    <!-- {{ tableTaskList }} -->
    <!-- -->
    <el-table
      :ref="'subTask'"
      style="width: 100%"
      :data="tableTaskList"
      border
      stripe
      @selection-change="handleSubTaskSelectionChangeFn"
    >
      <el-table-column v-if="selection" type="selection" width="55" align="center" />
      <el-table-column type="index" :index="indexFn" align="center" label="序号" width="50" />
      <el-table-column prop="data.witnessSubTaskStatusEnum" label="任务阶段" width="80">
        <template slot-scope="scope">
          <span class="">
            {{ scope.row.data.witnessSubTaskName }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="witnessSubTaskStatusEnum" label="任务状态" width="80">
        <template slot-scope="scope">
          <span class="task-tag">
            <span :class="['', scope.row.data.witnessSubTaskStatusEnum]">
              {{ witnessSubTaskStatusFn(scope.row.data.witnessSubTaskStatusEnum) }}
            </span></span
          >
        </template>
      </el-table-column>
      <el-table-column prop="projectName" label="项目名称" min-width="180">
        <template slot-scope="scope">
          <span>
            {{ scope.row.data.projectName }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="bidSectionName" label="标段名称" min-width="150">
        <template slot-scope="scope">
          <span class="line2" :title="scope.row.data.bidSectionName">
            {{ scope.row.data.bidSectionName }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="bidSectionCode" label="标段编号" min-width="150">
        <template slot-scope="scope">
          <span class="line2" :title="scope.row.data.bidSectionCode">
            {{ scope.row.data.bidSectionCode }}
          </span>
        </template>
      </el-table-column>
      <!--      <el-table-column prop="bidSectionName" label="行业类别" min-width="120">
        <template slot-scope="scope">
          <span>
            {{ industryFn(scope.row.data.industry) }}
          </span>
        </template>
      </el-table-column>-->
      <!-- <el-table-column prop="projectName" label="见证人" min-width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.data.witnessUserName">
            {{ scope.row.data.witnessUserName }}({{
              scope.row.data.witnessUserCode
            }})
          </span>
        </template>
      </el-table-column> -->
      <el-table-column prop="startTime" label="开始时间" width="110">
        <template slot-scope="scope">
          <!-- <span>
            {{ scope.row.data.startTime }}
          </span> -->
          <div v-if="scope.row.data.startTime">
            <div v-for="item in scope.row.data.startTime.split(' ')" :key="item">
              {{ item }}
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="data.witnessEndTime" label="结束时间" width="110">
        <template slot-scope="scope">
          <div v-if="scope.row.data.witnessEndTime">
            <div v-for="item in scope.row.data.witnessEndTime.split(' ')" :key="item">
              {{ item }}
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="" label="交易方式" width="80">
        <template slot-scope="scope">
          {{ tenderModeFn(scope.row.data.tenderMode) }}
        </template>
      </el-table-column>
      <el-table-column prop="data.witnessAllocateUserName" label="任务来源" min-width="80" />
      <!-- <el-table-column
        prop="data.witnessAllocateUserName"
        label="分配人"
        min-width="80"
      >
      </el-table-column> -->
      <el-table-column prop="data.witnessSubTaskAllocateTime" label="分配时间" width="110">
        <template slot-scope="scope">
          <div v-if="scope.row.data.witnessSubTaskAllocateTime">
            <div v-for="item in scope.row.data.witnessSubTaskAllocateTime.split(' ')" :key="item">
              {{ item }}
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" header-align="center" width="190">
        <template slot-scope="scope">
          <!-- 2.子任务按钮显示逻辑：
待分配：【分配见证人】
待见证：【更改见证人】
见证中：【进入见证】【更改见证人】
待审核：【审核见证记录】
已完成：【查看见证记录】 -->
          <!-- v-if="scope.row.type == 'start'" -->
          <el-button
            v-if="pageOpersFn('OPERATE_VIEW_SUB_WITNESS_TASK_DETAIL', scope.row.pageOpers)"
            type="text"
            size="default"
            @click="detailShowFn(scope)"
          >
            详情
          </el-button>
          <el-button
            v-if="pageOpersFn('OPERATE_VIEW_SUB_WITNESS_TASK_RECORD', scope.row.pageOpers)"
            type="text"
            size="default"
            @click="recordShowFn(scope)"
          >
            查看见证记录
          </el-button>
          <el-button
            v-if="pageOpersFn('OPERATE_APPROVE_WITNESS_RECORD', scope.row.pageOpers)"
            type="text"
            size="default"
            @click="recordClickFn(scope)"
          >
            审核见证记录
          </el-button>
          <!-- <template v-for="item in scope.row.pageOpers"> -->
          <!-- 工作人员-详情 -->

          <el-button
            v-if="pageOpersFn('OPERATE_UPDATE_WITNESS_USER', scope.row.pageOpers)"
            type="text"
            size="default"
            @click="updateClickFn(scope)"
          >
            更改见证人
          </el-button>
          <el-button
            v-if="pageOpersFn('OPERATE_ALLOCATE_WITNESS_USER', scope.row.pageOpers)"
            type="text"
            size="default"
            @click="allocateClickFn(scope)"
          >
            分配见证人
          </el-button>
          <el-button
            v-if="pageOpersFn('OPERATE_ENTRY_WITNESS_SUB_TASK', scope.row.pageOpers)"
            type="text"
            size="default"
            @click="enterClickFn(scope)"
          >
            进入见证
          </el-button>
          <el-button
            v-if="pageOpersFn('OPERATE_START_SUB_WITNESS_TASK', scope.row.pageOpers)"
            type="text"
            size="default"
            @click="startClickFn(scope)"
          >
            开始见证
          </el-button>
          <el-button
            v-if="pageOpersFn('OPERATE_TRANSFER_WITNESS_USER', scope.row.pageOpers)"
            type="text"
            size="default"
            @click="allocateUserClickFn(scope)"
          >
            移交见证
          </el-button>
          <el-button
            v-if="pageOpersFn('OPERATE_VIEW_WITNESS_VIDEO', scope.row.pageOpers)"
            type="text"
            size="default"
            @click="openMediaFn(scope.row)"
          >
            查看视频
          </el-button>
          <!-- </template> -->
        </template>
      </el-table-column>
    </el-table>
    <!-- 见证记录 -->
    <!-- <WitnessRecord
      :show="recordShow"
      :type="recordType"
      :id="subtaskRow.witnessSubTaskId"
      :rowData="currentWitness"
      :initData="TASKOBJ"
      @close="recordCloseFn"
      @submit="recordSubmitFn"
    /> -->
    <WitnessRecord
      :id="currentWitness.witnessSubTaskId"
      :show="recordShow"
      :type="recordType"
      :header-title="recordTitle"
      :row-data="currentWitness"
      :data="recordData"
      :init-data="TASKOBJ"
      @close="recordCloseFn"
      @submit="recordSubmitFn"
    />
    <!-- 移交见证 -->
    <el-dialog title="移交见证" :visible.sync="yiJiaoVisible" width="500" draggable custom-class="dialog-demo">
      <div> <span class="warning">!</span>移交见证任务后该任务将从当前列表中移除，请确认无误后进行移交。 </div>
      <el-form ref="formSubt" :model="formSubt" label-width="auto" label-max-width="140px" :rules="rulesyj">
        <el-form-item label="移交给" prop="witnessSubTaskIdList">
          <el-select v-model="formSubt.witnessSubTaskIdList" placeholder="请选择" @change="yiJiaoChange">
            <el-option v-for="(item, index) in subtaskList" :key="index" :label="item.userName" :value="item.userId" />
          </el-select>
        </el-form-item>
        <el-form-item label="移交原因" prop="reason">
          <el-input
            v-model="formSubt.reason"
            type="textarea"
            placeholder="请输入移交原因"
            :rows="4"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        <el-form-item class="dialog-footer">
          <span>
            <el-button type="primary" @click="submitYj('formSubt')">确定</el-button>
            <el-button @click="cancelYj('formSubt')">取消</el-button>
          </span>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- <el-dialog
      title="移交见证"
      :visible.sync="allocateVisible"
      width="530"
      @close="">
      <span></span>
      <span slot="footer">
        <el-button @click=" = false">Cancel</el-button>
        <el-button type="primary" @click="">OK</el-button>
      </span>
    </el-dialog> -->
  </div>
</template>
<script>
  import { FindArrayFn } from "../../../utils/utils";
  import WitnessRecord from "../../../components/dialog/WitnessRecord.vue";
  import { subtaskStart, subtaskFinish, subtaskAllocateUser, subtaskPermissionUser } from "../../../api/api.js";
  import { GZAPI_EvaluationTime } from "../../../../gz_plugin/api";
  export default {
    components: { WitnessRecord },
    props: {
      tableData: {
        type: Array,
        default() {
          return [];
        }
      },
      // eslint-disable-next-line vue/prop-name-casing
      TASKOBJ: {
        type: Object,
        default() {
          return {};
        }
      },
      currentPage: {
        type: Number,
        default: 1
      },
      pageSize: {
        type: Number,
        default: 10
      },
      selection: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        subtaskList: [],
        recordData: [],
        recordShow: false,
        allocateVisible: false,
        yiJiaoVisible: false,
        recordType: "",
        recordTitle: "",
        currentWitness: {},
        subtaskRow: {},
        tableTaskList: [],
        rulesyj: {
          witnessSubTaskIdList: [{ required: true, message: "移交人不能为空", trigger: "blur" }],
          reason: [{ required: true, message: "移交原因不能为空", trigger: "blur" }]
          // witnessSubTaskIdList: [
          //   { required: true, message: "事项说明不能为空", trigger: "change" },
          // ],
        },
        formSubt: {
          witnessSubTaskIdList: "",
          reason: "",
          userId: ""
        }
      };
    },
    watch: {
      tableData(val) {
        this.tableTaskList = val;
      }
    },
    methods: {
      pageOpersFn(val, Arr) {
        return Arr.some((item) => item.code == val);
      },
      indexFn(index) {
        return index + 1 + (this.currentPage - 1) * this.pageSize;
      },
      recordCloseFn() {
        this.recordShow = false;
        this.recordTitle = "";
      },
      recordSubmitFn() {},
      detailShowFn({ row }) {
        console.log("row", row);
        this.currentWitness = row.data;
        this.recordShow = true;
        this.recordTitle = "项目详情";
      },
      recordShowFn(row) {
        console.log("row", row);
        this.currentWitness = row.data;
        this.recordShow = true;
        this.recordTitle = "查看见证记录";
      },
      // 进入见证
      enterClickFn({ row }) {
        this.$router.push({
          name: "Workbench",
          query: { id: row.data.witnessSubTaskId }
        });
      },
      // 开始见证
      startClickFn({ row, $index }) {
        console.log("row", row);
        this.currentWitness = row.data;
        this.currentWitness.index = $index;
        this.subtaskStartFn();
      },
      // 开始见证
      async subtaskStartFn() {
        const p = { witnessSubTaskId: this.currentWitness.witnessSubTaskId };
        try {
          const res = await GZAPI_EvaluationTime.subtaskStart(p);
          if (res.success) {
            this.$message({
              type: "success",
              message: "操作成功",
              single: true
            });
            // let i = 0;
            // this.tableTaskList[this.currentWitness.index].pageOpers.forEach((item, index) => {
            //   if (item.code == "OPERATE_START_SUB_WITNESS_TASK") {
            //     i = index;
            //   }
            // });
            this.$router.push({
              name: "Workbench",
              query: {
                id: this.currentWitness.witnessSubTaskId
              }
            });
            // this.$set(
            //   this.tableTaskList[this.currentWitness.index].pageOpers[i],
            //   "code",
            //   "OPERATE_ENTRY_WITNESS_SUB_TASK"
            // );
          } else {
            this.$message({
              type: "error",
              message: res.message || "获取数据失败，请稍后再试",
              single: true
            });
          }
        } catch (err) {
          console.error(err);
          this.$message({
            type: "error",
            message: "获取数据失败，请稍后再试",
            single: true
          });
        }
      },
      //  结束见证
      async subtaskFinishFn(row, index) {
        console.log(row, index);
        const p = {
          witnessSubTaskId: this.id
        };
        try {
          const res = await GZAPI_EvaluationTime.subtaskFinish(p);
          if (res.success) {
            this.$message({
              type: "success",
              message: res.message || "操作成功",
              single: true
            });
          } else {
            this.$message({
              type: "error",
              message: res.message || "获取数据失败，请稍后再试",
              single: true
            });
          }
        } catch (err) {
          console.error(err);
          this.$message({
            type: "error",
            message: "获取数据失败，请稍后再试",
            single: true
          });
        }
      },
      // 移交见证
      async subtaskAllocateFn(row) {
        this.yiJiaoVisible = true;
        const p = {
          witnessSubTaskIdList: [row.data.witnessSubTaskId]
        };
        try {
          const res = await subtaskPermissionUser(p);
          if (res.success) {
            this.subtaskList = res.data.data;
          } else {
            this.$message({
              type: "error",
              message: res.message || "获取数据失败，请稍后再试",
              single: true
            });
          }
        } catch (err) {
          console.error(err);
          this.$message({
            type: "error",
            message: "获取数据失败，请稍后再试",
            single: true
          });
        }
      },
      cancelYj(formSubt) {
        this.$refs[formSubt].resetFields();
        this.formSubt.witnessSubTaskIdList = "";
        this.yiJiaoVisible = false;
      },
      submitYj(formSubt) {
        this.$refs[formSubt].validate((valid) => {
          if (valid) {
            this.subtaskAllocateUserFn();
            this.yiJiaoVisible = false;
          } else {
            return false;
          }
        });
      },
      yiJiaoChange(e) {
        this.formSubt.userId = e;
      },
      async subtaskAllocateUserFn() {
        const p = {
          userId: this.formSubt.userId,
          reason: this.formSubt.reason,
          witnessSubTaskAllocateType: "TRANSFER_ALLOCATE",
          witnessSubTaskIdList: [this.currentWitness.data.witnessSubTaskId]
        };
        try {
          const res = await subtaskAllocateUser(p);
          if (res.success) {
            this.$message({
              type: "success",
              message: "移交成功",
              single: true
            });
            this.yiJiaoVisible = false;
            this.$parent.handleSearchFn();
            this.formSubt = {};
          } else {
            this.$message({
              type: "error",
              message: res.message || "获取数据失败，请稍后再试",
              single: true
            });
          }
        } catch (err) {
          console.error(err);
          this.$message({
            type: "error",
            message: "获取数据失败，请稍后再试",
            single: true
          });
        }
      },
      openMediaFn(row) {
        console.log("row openMediaFn", row);
        // 管理员，查看视频
        const { witnessSubTaskId } = row;
        let str = new Date().getTime();
        str += `&witnessSubTaskId=${witnessSubTaskId}`;

        window.open(`${process.env.VUE_APP_MEDIA}${str}`, "witness_media");
      },
      allocateUserClickFn({ row }) {
        this.currentWitness = row;
        this.subtaskAllocateFn(row);
      },
      tenderModeFn(val) {
        const array = this.TASKOBJ.industryTypeAndTenderMode;
        const obj = FindArrayFn(array, val) || {};
        return obj.label;
      },
      // 任务状态
      witnessSubTaskStatusFn(val) {
        const array = this.TASKOBJ.witnessSubTaskStatus;
        const obj = FindArrayFn(array, val) || {};
        return obj.label;
      },
      witnessItemStatusFn(val) {
        const array = this.TASKOBJ.witnessItemStatus;
        const obj = FindArrayFn(array, val) || {};
        return obj.label;
      },
      // 行业类型转文字
      industryFn(val) {
        const array = this.TASKOBJ.industryTypeAndIndustry;
        const obj = FindArrayFn(array, val) || {};
        return obj.label;
      },
      // 子任务表格多选
      handleSubTaskSelectionChangeFn(val) {
        console.log("val", val);
        this.multipleSubTaskSelection = val;
        this.assignData = val;
      }
    }
  };
</script>
<style lang="scss" scoped>
  .warning {
    width: 20px;
    height: 20px;
    display: inline-block;
    background: #e6ad00;
    color: #fff;
    text-align: center;
    border-radius: 50%;
    margin-right: 5px;
    margin-bottom: 20px;
  }
  .dialog-footer {
    text-align: right;
  }
</style>
